#!/usr/bin/env python
#-*- coding:utf-8 -*-

##### Copyright: Enrico Finetti 2010-11 [kerry.igg@hotmail.it] #####
#####  (DATE START: 16.dec.2010 - DATE END: work in progress)  #####

# I'm going to create a visual logger form.
# I'm doing this just for practise but I hope that it can become useful for someone searching for something like this.
# The whole interface of the program is in English.
 
# Work Steps:
# 1. Creating the form using pyGTK
# 2. Creating a "database" and a reader of this using an invisible file that contains all the datas about users which SIGN UP
# 3. Creating a code that controls the matching of Username and Password (LOG IN)
# 4. After the LOG IN, creating a code that gives the possibility to exit, modify or delete your profile

#------------------------------------#
#     Completed steps: [1 2 3 -]     #
#------------------------------------#

import os
import pygtk
pygtk.require('2.0')
import gtk

### Step 1. Creating the form using pyGTK

#I create the class 'form'
class form:

	#I define what the form shows
	def __init__(self):
	
		#FORM (state-title-position-dimension)
		self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.win.set_title("Login") 
		self.win.set_position(gtk.WIN_POS_CENTER)
		self.win.set_default_size(350, 250)
	
		#TABLE
		self.box = gtk.Table(20, 6, homogeneous=True)
		
		#LABEL 1 -> Username
		self.label1 = gtk.Label("Username:  ")
		self.label1.set_alignment(0.0 - 0.0, 0.0 + 0.4)
		self.box.attach(self.label1, 1, 2, 7, 9)
		
		#LABEL 2 -> Password
		self.label2 = gtk.Label(" Password:  ")
		self.label2.set_alignment(0.0 - 0.0, 0.0 + 0.4)
		self.box.attach(self.label2, 1, 2, 9, 11)
		
		#ENTRY 1 -> *Username*
		self.entry1 = gtk.Entry(max = 100)
		self.box.attach(self.entry1, 2, 5, 7, 9)
		
		#ENTRY 2 -> *Password*
		self.entry2 = gtk.Entry(max = 50)
		#set "*" as the char will be shown during the typing of the password
		self.entry2.set_visibility(False)
		self.entry2.set_invisible_char("*")
		self.box.attach(self.entry2, 2, 5, 9, 11)
		
		#BUTTON 1 -> Sign Up
		self.button1 = gtk.Button("Sign Up")
		self.button1.connect("clicked", self.b1clicked)
		self.box.attach(self.button1, 2, 3, 12, 14)
		
		#BUTTON 2 -> Login
		self.button2 = gtk.Button("Login")
		self.button2.connect("clicked", self.DataReader)
		self.box.attach(self.button2, 3, 4, 12, 14)
		
		#I add the TABLE to the FORM and make it visible
		self.win.add(self.box)
		self.win.show_all()
		

	
### Step 2. Creating a "database" and a reader of this using an invisible file that contains all the datas about users which SIGN UP
	
	#I define what happens when you click BUTTON 1 (registration)
	def b1clicked(self, widget):
	
		#I create the text file "database" called "LoginData" and I make it invisible
		b1click = open(os.getenv("HOME") + "/.LoginData", "a")
		
		#Code that will read what's written in the "database" and convert it in a dictionary
		LoginData = open(os.getenv("HOME") + "/.LoginData", "r")
		reader = LoginData.read()
		readerSTR = "{" + reader + "}"
		readerDICT = eval(readerSTR)
		
		#If the Username is less than 4 characters in lenght
		if self.entry1.get_text_length() < 4:
			msg = gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_CLOSE, message_format = ("Username must be at least 4 characters in lenght."))
			if msg.run() == gtk.RESPONSE_CLOSE:
				msg.destroy()
				
		#if the is less than 1 characters in lenght
		elif self.entry2.get_text_length() < 1:
			msg2 = gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_CLOSE, message_format = ("Password must be at least 1 character in lenght."))
			if msg2.run() == gtk.RESPONSE_CLOSE:
				msg2.destroy()
		#If the Username already exists
		elif readerDICT.has_key(self.entry1.get_text()) == True:
			msg3 = gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_CLOSE, message_format = ("This username has been already taken."))
			if msg3.run() == gtk.RESPONSE_CLOSE:
				msg3.destroy()
		#Else	
		else:
			#I write in the created file a string containing ENTRY 1 (the username) and ENTRY 2 (the password)
			b1click.write('"' + self.entry1.get_text() + '"' + ": " + '"' + self.entry2.get_text() + '"' + ", " )
			
			#And a messagebox shows itself to confirm the registration
			msg4 = gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_INFO, buttons = gtk.BUTTONS_OK, message_format = ("Account created."))
			if msg4.run() == gtk.RESPONSE_OK:
				msg4.destroy()


	
### Step 3. Creating a system that controls the matching of Username and Password (LOG IN)
	
	#I define what happens when you click BUTTON 2 (log in)
	def DataReader(self, widget):
		
		try:
			#Same code that will read what's written in the "database" and convert it in a dictionary
			LoginData = open(os.getenv("HOME") + "/.LoginData", "r")
			reader = LoginData.read()
			readerSTR = "{" + reader + "}"
			readerDICT = eval(readerSTR)
			
			#If the username doesn't exist
			if readerDICT.has_key(self.entry1.get_text()) == False:
				msg6 = gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_CLOSE, message_format = ("Username and password do not match, check for possible spelling errors and retry."))
				if msg6.run() == gtk.RESPONSE_CLOSE:
					msg6.destroy()
			#Else
			else:
				#If Passwords match, it's all OK, then it opens the account window, closing the login form
				if readerDICT[self.entry1.get_text()] == self.entry2.get_text():
					msg5 = gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_INFO, buttons = gtk.BUTTONS_OK, message_format = ("Logged in successfully."))
					if msg5.run() == gtk.RESPONSE_OK:
						msg5.destroy()
						self.winLogIn = gtk.Window(gtk.WINDOW_TOPLEVEL)
						self.winLogIn.set_title(self.entry1.get_text() + "'s account") 
						self.winLogIn.set_position(gtk.WIN_POS_CENTER)
						self.winLogIn.set_default_size(400, 300)
						self.winLogIn.show_all()
						self.win.destroy()		
			
			#Else give the same message as before		
				else:
					msg6 = gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_CLOSE, message_format = ("Username and password do not match, check for possible spelling errors and retry."))
					if msg6.run() == gtk.RESPONSE_CLOSE:
						msg6.destroy()
						
		#Exception to the error that would give if you click LOG IN the first time you open this program
		#Such a "no database where the program can read" error	
		except IOError:
			msg7 = gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_CLOSE, message_format = ("You have to register at least an account before you can log in."))
			if msg7.run() == gtk.RESPONSE_CLOSE:
				msg7.destroy()
		
		
		
### Step 4. After the LOG IN, creating a code that gives the possibility to exit, modify or delete your profile	
	pass
	
#Run commands
	def main(self):
		gtk.main()

if __name__ == "__main__":
	first = form()
	first.main()
	
